package org.mii.safeguard_v1.base.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.mii.safeguard_v1.base.entity.CtProvince;
import org.mii.safeguard_v1.base.entity.CtSP;
import org.mii.safeguard_v1.base.entity.DepRecordReport;
import org.mii.safeguard_v1.security.entity.User;
import org.mii.safeguard_v1.security.service.IUserManager;
import org.mii.safeguard_v1.util.JsonBuilderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.springside.modules.web.struts2.Struts2Utils;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "init.action", type = "redirect"),
		@Result(name = CrudActionSupport.NOTICE, location = "notice.jsp", type = "redirect"),
		@Result(name = CrudActionSupport.DENY_ACCESS, location = "common/403.jsp", type = "redirect") })
public class InitAction extends ActionSupport {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	IUserManager userManager;

	/**
	 * 该方法为前台登录成功后走的方法，携带参数tag=1，主要用来构建登录后的页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/frame")
	public String frame() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		HttpSession session = Struts2Utils.getSession();

		// 获取当前登录的用户
		org.springframework.security.userdetails.User securityUser = SpringSecurityUtils.getCurrentUser();
		String userName = securityUser.getUsername();
		User user = userManager.findByUniqueProperty("loginName", userName);

		// 获取传递来的参数 其中tag为top页面中一级标题的序号，subtag为top页面中二级标题的序号
		String tag = request.getParameter("tag");
		String subTag = request.getParameter("subTag");

		// 将用户登录名称和所属单位名称放进session
		session.setAttribute("loginName", user.getLoginName());
		try {
			session.setAttribute("deptName", user.getDepRecordReport().getDepName());
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		// 将tag和subtag放进session
		session.setAttribute("tag", tag);
		session.setAttribute("subTag", subTag);
		// 根据tag来进行页面跳转 如果tag=1，即为系统首页，应显示新闻等信息;如果tag !=
		// 1，即为定级备案、安全评测等页面，应该构建左侧的树

		// 调整frame.jsp中iframe的内容
		if ("1".equalsIgnoreCase(tag)) {
			request.setAttribute("url", "index!index.action");
		} else {
			request.setAttribute("url", "content!content.action");
		}
		// 返回frame.jsp页面
		return SUCCESS;
	}

	@Action("/index")
	public String index() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		request.setAttribute("totalRows", 0);
		return SUCCESS;
	}

	@Action("/content")
	public String content() throws Exception {

		initPageData();
		return SUCCESS;
	}

	/**
	 * 初始化页面数据 包括ct_sp 和 province 两个list
	 */
	@SuppressWarnings("unchecked")
	public void initPageData() {
		HttpServletRequest request = Struts2Utils.getRequest();
		HttpSession session = Struts2Utils.getSession();
		String url = "http://www.google.com";
		// 获得当前登录用户
		org.springframework.security.userdetails.User securityUser = SpringSecurityUtils.getCurrentUser();
		String userName = securityUser.getUsername();
		User user = userManager.findByUniqueProperty("loginName", userName);
		// 获得当前登录用户的单位
		DepRecordReport dept = user.getDepRecordReport();
		// 获得当前登录用户单位 的 单位类型
		CtSP ctSP = dept.getCtSP();
		// 获得当前登录用户单位 的 省份
		CtProvince ctProvince = dept.getCtProvince();
		// 获得单位类型的id
		int spId = ctSP.getId();
		// 获得省份的id
		String proId = dept.getCtProvince().getDisId();
		// 根据tag和subtag来构建以下的两个list
		String tag = (String) session.getAttribute("tag");
		String subTag = (String) session.getAttribute("subTag");
		List<CtSP> ctSPList = null;
		List<CtProvince> ctProList = null;
		// 如果为定级备案
		if ("2".equalsIgnoreCase(tag)) {
			// 如果为定级备案->单位信息 或者 定级备案->定级对象 其实取出的单位类型和省份的值都是一致的，只是前台展示的方式不同
			if ("1".equalsIgnoreCase(subTag) || "2".equalsIgnoreCase(subTag)) {
				// 如果单位类型为审核单位，即parentid为0，就取出自己和parentid指向自己的数据
				if (ctSP.getParentid() == 0) {
					ctSPList = userManager.findByHql("from CtSP c where c.parentid=? or c.id=? order by c.sysid asc",
							ctSP.getId(), ctSP.getId());
				}
				// 如果单位类型为备案单位，即parentid>0，就取出自己
				else if (ctSP.getParentid() > 0) {
					ctSPList = new ArrayList<CtSP>(1);
					ctSPList.add(ctSP);
				}

				// 如果省份的disid是集团，即100000，就取出所有的数据('全国' 除外)
				if (ctProvince.getDisId().equalsIgnoreCase("100000")) {
					ctProList = userManager
							.findByHql("from CtProvince c where c.disId != '100001' order by c.position asc");
				}
				// 如果省份的disid不是集团，就取出自己的省
				else {
					ctProList = new ArrayList<CtProvince>(1);
					ctProList.add(ctProvince);
				}

			}

		} else {

		}
		// JsonBuilderUtil<CtProvince> provJson = new
		// JsonBuilderUtil<CtProvince>();
		// ctSpJson.buildJsonData(ctSPList, "id", "name");

		System.out.println("deptName为：   " + session.getAttribute("deptName"));
		System.out.println("单位类型为：" + JsonBuilderUtil.getInstance().buildJsonData(ctSPList, "id", "name", "level"));
		System.out.println("省为：" + JsonBuilderUtil.getInstance().buildJsonData(ctProList, "position", "name"));
		request.setAttribute("ctspJson", JsonBuilderUtil.getInstance().buildJsonData(ctSPList, "id", "name", "level"));
		request.setAttribute("provJson", JsonBuilderUtil.getInstance().buildJsonData(ctProList, "position", "name"));
		request.setAttribute("deptName", session.getAttribute("deptName"));
		request.setAttribute("url", url);
		session.setAttribute("spId", spId);
		session.setAttribute("proId", proId);
	}

}
